﻿#include"XQChartView_XYSeries.h"
#include"XQBubbleWidget.h"
#include<QMenu>
#include<QChart>
#include<QToolTip>
#include<QValueAxis>
#include<QXYSeries>
XQChartView_XYSeries::XQChartView_XYSeries(QWidget* parent)
	:XQChartView(parent)
{
	init();
}

XQChartView_XYSeries::~XQChartView_XYSeries()
{
}

QXYSeries* XQChartView_XYSeries::selectSeries() const
{
	return m_selectSeries;
}

void XQChartView_XYSeries::setSelectSeries(QXYSeries* series)
{
	m_selectSeries = series;
}

void XQChartView_XYSeries::setShowToolTip(std::function<QString(QXYSeries*, const QPointF&)>&& showFunc)
{
	m_showFunc = showFunc;
}

void XQChartView_XYSeries::init()
{
	XQChartView::init();
	m_bubble = new XQBubbleWidget(this);
	m_bubble->setFont(QFont("宋体", 8));
	m_showFunc = [this](QXYSeries* series, const QPointF& point) {
		QString text;
		auto name = series->name();
		if (!name.isEmpty())
			text += (name + "\r\n");
		text+= QString("X: %1\nY: %2").arg(point.x()).arg(point.y());
		return text;
	};
}

void XQChartView_XYSeries::mouseMoveEvent(QMouseEvent* ev)
{
	
	static int index = -1;
	 QXYSeries* &series = m_selectSeries;
	//取消上次的选中
	if (series && index >= 0)
		series->setPointSelected(index, false);
	// 获取鼠标悬停点附近的最近点的索引
	for (auto& AbstractSeries : chart()->series())
	{
		QXYSeries* s = static_cast<QXYSeries*>(AbstractSeries);
		auto dex=findNearestPointIndex(s, ev->pos());
		index = dex; series = s;
		if (dex >= 0)
			break;
	}
	// 如果找到最近点，则显示该点并设置工具提示
	if (series&&index >= 0 && index < series->count()) {
		QPointF Point = series->at(index);
		//qDebug() << m_showFunc(series, Point);
		series->setPointSelected(index,true);
		m_bubble->showText(chart()->mapToPosition(Point).toPoint(), m_showFunc(series, Point),Derection::down);
		/*QToolTip::showText(mapToGlobal(chart()->mapToPosition(Point).toPoint()), m_showFunc(series, Point),this, QRect(),999999);*/
	}
	else 
	{
		m_bubble->hide();
	}
	XQChartView::mouseMoveEvent(ev);
}

int XQChartView_XYSeries::findNearestPointIndex(QXYSeries* series,const QPoint& pos)
{
	QPointF chartPoint = chart()->mapToValue(pos);
	int index = -1;
	qreal minDistance = std::numeric_limits<qreal>::max();

	for (int i = 0; i < series->count(); ++i) {
		QPointF point = series->at(i);
		qreal distance = qAbs(point.x() - chartPoint.x());

		if (distance < minDistance) {
			minDistance = distance;
			index = i;
		}
	}
	//数值转图标上的坐标
	QPointF Point = chart()->mapToPosition(series->at(index), series);
	qreal distanceX = qAbs(Point.x() - pos.x());
	qreal distanceY = qAbs(Point.y() - pos.y());
	if (distanceX > 10 || distanceY > 10)
		return -1;//判断是否在鼠标附近
	return index;
}
